<template>
  <transition>
    <div class="backtop" v-show="backShow" @click="backTop">
      <icon name="back-top" />
    </div>
  </transition>
</template>

<script>
export default {
  props: {
    height: {
      type: Number,
      default: 500
    },
    duration: {
      type: Number,
      default: 300
    }
  },
  inject: ["app"],
  data() {
    return {
      backShow: false,
      dom: null
    };
  },
  watch: {
    "app.scrollTop"(val) {
      this.backShow = val >= this.height;
    }
  },
  methods: {
    backTop() {
      let scrollTop = this.app.scrollTop;
      const doc = document;
      for (let i = 60; i >= 0; i--) {
        setTimeout(
          i => {
            let val = (scrollTop * i) / 60;
            doc.documentElement.scrollTop = val;
            doc.body.scrollTop = val;
          },
          (this.duration / 60) * (60 - i),
          i
        );
      }
    }
  }
};
</script>

<style lang="less" scoped>
.backtop {
  position: fixed;
  bottom: 240px;
  right: 0px;
  z-index: 100;
  width: 44px;
  height: 44px;
  background: @white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: @primary-color;
  box-shadow: 0 0 10px 0 hsla(0, 0%, 80.4%, 0.5);
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;

  .icon-back-top {
    width: 20px;
    height: 20px;
  }

  &.v {
    &-enter-active,
    &-leave-active {
      transition: all 0.3s;
    }

    &-enter,
    &-leave-to {
      opacity: 0;
    }
  }
}
</style>
